// selectionGroupAI.cpp

#include "CvGameCoreDLL.h"
#include "CvSelectionGroupAI.h"
#include "CvPlayerAI.h"
#include "CvMap.h"
#include "CvPlot.h"
/* BetterAI by mrgenie 21.01.2007 start*/
#include "CvTeamAI.h"
/* BetterAI by mrgenie 21.01.2007 end*/
#include "CvDLLEntityIFaceBase.h"
#include "CvGameCoreUtils.h"
#include "FProfiler.h"
/* BetterAI by mrgenie 21.01.2007 start*/
#include "CVInfos.h"
/* BetterAI by mrgenie 21.01.2007 end*/

// Public Functions...
CvSelectionGroupAI::CvSelectionGroupAI()
{
	AI_reset();
}


CvSelectionGroupAI::~CvSelectionGroupAI()
{
	AI_uninit();
}


void CvSelectionGroupAI::AI_init()
{
	AI_reset();

	//--------------------------------
	// Init other game data
}


void CvSelectionGroupAI::AI_uninit()
{
}


void CvSelectionGroupAI::AI_reset()
{
	AI_uninit();

	m_iMissionAIX = INVALID_PLOT_COORD;
	m_iMissionAIY = INVALID_PLOT_COORD;

	m_bForceSeparate = false;

	m_eMissionAIType = NO_MISSIONAI;

	m_missionAIUnit.reset();

	/* BetterAI by mrgenie 21.01.2007 start*/
	m_bGroupAttack = false;
	/* BetterAI by mrgenie 21.01.2007 end*/
}


void CvSelectionGroupAI::AI_separate()
{
	CLLNode<IDInfo>* pEntityNode;
	CvUnit* pLoopUnit;

	/* BetterAI by mrgenie 21.01.2007 start*/
#ifdef DEBUG_AI_UPDATE_GROUPS
	// debugging
	if (true)
	{
		DEBUGLOG("AI_separate(%d) [size %d]\n", shortenID(m_iID), getNumUnits());
	}
#endif
	/* BetterAI by mrgenie 21.01.2007 end*/

	pEntityNode = headUnitNode();

	while (pEntityNode != NULL)
	{
		pLoopUnit = ::getUnit(pEntityNode->m_data);
		pEntityNode = nextUnitNode(pEntityNode);

		pLoopUnit->joinGroup(NULL);
	}
}

/* BetterAI by mrgenie 21.01.2007 start*/
void CvSelectionGroupAI::AI_seperateNonAI(UnitAITypes eUnitAI)
{
	CLLNode<IDInfo>* pEntityNode;
	CvUnit* pLoopUnit;

#ifdef DEBUG_AI_UPDATE_GROUPS
	// debugging
	if (true)
	{
		DEBUGLOG("AI_separateNonAI(%d) [size %d]\n", shortenID(m_iID), getNumUnits());
	}
#endif

	pEntityNode = headUnitNode();

	while (pEntityNode != NULL)
	{
		pLoopUnit = ::getUnit(pEntityNode->m_data);
		pEntityNode = nextUnitNode(pEntityNode);
		if (pLoopUnit->AI_getUnitAIType() != eUnitAI)
		{
			pLoopUnit->joinGroup(NULL);
		}
	}
}
/* BetterAI by mrgenie 21.01.2007 end*/

// Returns true if the group has become busy...
bool CvSelectionGroupAI::AI_update()
{
	CLLNode<IDInfo>* pEntityNode;
	CvUnit* pHeadUnit;
	CvUnit* pLoopUnit;
	bool bDead;
	bool bFollow;

	PROFILE("CvSelectionGroupAI::AI_update");

	FAssert(getOwnerINLINE() != NO_PLAYER);

	if (!AI_isControlled())
	{
		return false;
	}

	if (getNumUnits() == 0)
	{
		return false;
	}

	/* BetterAI by mrgenie 21.01.2007 start*/
#ifdef DEBUG_AI_UPDATE_GROUPS
	// debugging
	if (!GET_PLAYER(getOwnerINLINE()).isHuman())
	{
		pHeadUnit = getHeadUnit();
		CvWString szPlayerName = GET_PLAYER(getOwnerINLINE()).getName();
		CvWString szUnitString;
		if (pHeadUnit != NULL)
		{
			CvWString szUnitName = GC.getUnitInfo(pHeadUnit->getUnitType()).getDescription();
			szUnitString.Format(L"%s(%d)", szUnitName.GetCString(), shortenID(pHeadUnit->getID()));
		}
		else
			szUnitString.Format(L"--no unit--");

		CvWString szActivityString;
		getActivityTypeString(szActivityString, m_eActivityType);

		DEBUGLOG("AI_update:%S group(%d,%S), lead by %S [size %d%s%s]\n", szPlayerName.GetCString(),
			shortenID(getID()), szActivityString.GetCString(), szUnitString.GetCString(), getNumUnits(),
			AI_isForceSeparate() ? ",WILL_SEPARATE" : "",
			isForceUpdate() ? ",WILL_FORCE_UPDATE" : "");
	}
#endif
	/* BetterAI by mrgenie 21.01.2007 end*/
	if (isForceUpdate())
	{
		clearMissionQueue(); // XXX ???
		setActivityType(ACTIVITY_AWAKE);
		setForceUpdate(false);

		/* BetterAI by mrgenie 21.01.2007 start*/
		// if we are in the middle of attacking with a stack, cancel it
		AI_cancelGroupAttack();
		/* BetterAI by mrgenie 21.01.2007 end*/
	}

	FAssert(!(GET_PLAYER(getOwnerINLINE()).isAutoMoves()));

	int iTempHack = 0; // XXX

	bDead = false;

	/* BetterAI by mrgenie 21.01.2007 start*/
	bool bFailedAlreadyFighting = false;
	while (!bFailedAlreadyFighting && (m_bGroupAttack || readyToMove()))
	{
		iTempHack++;
		if (iTempHack > 100)
		{
			FAssert(false);
			if ((pHeadUnit = getHeadUnit()) != NULL) { pHeadUnit->finishMoves(); }
			break;
		}

		// if we want to force the group to attack, force another attack
		if (m_bGroupAttack)
		{
			m_bGroupAttack = false;

			bool bGroupAttacked = groupAttack(m_iGroupAttackX, m_iGroupAttackY, MOVE_DIRECT_ATTACK, bFailedAlreadyFighting);
		}
		// else pick AI action
		else
		{
			pHeadUnit = getHeadUnit();

			if (pHeadUnit == NULL)
			{
				break;
			}

			resetPath();

			if (pHeadUnit->AI_update())
			{
				// AI_update returns true when we should abort the loop and wait until next slice
				break;
			}
		}

		if (doDelayedDeath())
		{
			bDead = true;
			break;
		}

		// if no longer group attacking, and force separate is true, then bail, decide what to do after group is split up
		// (UnitAI of head unit may have changed)
		if (!m_bGroupAttack && AI_isForceSeparate())
		{
			AI_separate();	// pointers could become invalid...
			return false;
		}
	}

	if (!bFailedAlreadyFighting && !bDead)
	{
		if (!isHuman())
		{
			bFollow = false;

			// if we not group attacking, then check for follow action
			if (!m_bGroupAttack)
			{
				pEntityNode = headUnitNode();

				while ((pEntityNode != NULL) && readyToMove(true))
				{
					pLoopUnit = ::getUnit(pEntityNode->m_data);
					pEntityNode = nextUnitNode(pEntityNode);

					if (pLoopUnit->canMove())
					{
						resetPath();

						if (pLoopUnit->AI_follow())
						{
							bFollow = true;
							break;
						}
					}
				}
			}

			if (doDelayedDeath())
			{
				bDead = true;
			}

			if (!bDead)
			{
				if (!bFollow && readyToMove(true))
				{
					pushMission(MISSION_SKIP);
				}
			}
		}
	}
	/* BetterAI by mrgenie 21.01.2007 end*/

	if (bDead)
	{
		return false;
	}

	return (isBusy() || isCargoBusy());
}


// Returns attack odds out of 100 (the higher, the better...)
int CvSelectionGroupAI::AI_attackOdds(const CvPlot* pPlot, bool bPotentialEnemy) const
{
	CvUnit* pAttacker;

	FAssert(getOwnerINLINE() != NO_PLAYER);

	if (pPlot->getBestDefender(NO_PLAYER, getOwnerINLINE(), NULL, !bPotentialEnemy, bPotentialEnemy) == NULL)
	{
		return 100;
	}

	/* BetterAI by mrgenie 21.01.2007 start*/
	// pAttacker = AI_getBestGroupAttacker(pPlot, bPotentialEnemy);
	int iOdds = 0;
	pAttacker = AI_getBestGroupAttacker(pPlot, bPotentialEnemy, iOdds);
	/* BetterAI by mrgenie 21.01.2007 end*/

	if (pAttacker == NULL)
	{
		return 0;
	}

	/* BetterAI by mrgenie 21.01.2007 start*/
	// return pAttacker->AI_attackOdds(pPlot, bPotentialEnemy);
	return iOdds;
	/* BetterAI by mrgenie 21.01.2007 end*/
}

/* BetterAI by mrgenie 21.01.2007 start*/
// CvUnit* CvSelectionGroupAI::AI_getBestGroupAttacker(const CvPlot* pPlot, bool bPotentialEnemy, bool bForce, bool bNoBlitz) const
CvUnit* CvSelectionGroupAI::AI_getBestGroupAttacker(const CvPlot* pPlot, bool bPotentialEnemy, int& iUnitOdds, bool bForce, bool bNoBlitz) const
/* BetterAI by mrgenie 21.01.2007 end*/
{
	CLLNode<IDInfo>* pUnitNode;
	CvUnit* pLoopUnit;
	CvUnit* pBestUnit;
	int iPossibleTargets;
	int iValue;
	int iBestValue;
	/* BetterAI by mrgenie 21.01.2007 start*/
	int iOdds;
	int iBestOdds;
	/* BetterAI by mrgenie 21.01.2007 end*/

	iBestValue = 0;
	/* BetterAI by mrgenie 21.01.2007 start*/
	iBestOdds = 0;
	/* BetterAI by mrgenie 21.01.2007 end*/
	pBestUnit = NULL;

	pUnitNode = headUnitNode();

	/* BetterAI by mrgenie 21.01.2007 start*/
	bool bIsHuman = (pUnitNode != NULL) ? GET_PLAYER(::getUnit(pUnitNode->m_data)->getOwnerINLINE()).isHuman() : true;
	/* BetterAI by mrgenie 21.01.2007 end*/

	while (pUnitNode != NULL)
	{
		pLoopUnit = ::getUnit(pUnitNode->m_data);
		pUnitNode = nextUnitNode(pUnitNode);

		if (!pLoopUnit->isDead())
		{
			bool bCanAttack = false;
			if (pLoopUnit->getDomainType() == DOMAIN_AIR)
			{
				bCanAttack = pLoopUnit->canAirAttack();
			}
			else
			{
				bCanAttack = pLoopUnit->canAttack();

				if (bCanAttack && bNoBlitz && pLoopUnit->isBlitz() && pLoopUnit->isMadeAttack())
				{
					bCanAttack = false;
				}
			}

			if (bCanAttack)
			{
				/* BetterAI by mrgenie 21.01.2007 start*/
				if (bForce || pLoopUnit->canMove())
				{
					if (bForce || pLoopUnit->canMoveInto(pPlot, /*bAttack*/ true, /*bDeclareWar*/ bPotentialEnemy))
					{
						iOdds = pLoopUnit->AI_attackOdds(pPlot, bPotentialEnemy);

						iValue = iOdds;
						FAssertMsg(iValue > 0, "iValue is expected to be greater than 0");

						if (pLoopUnit->collateralDamage() > 0)
						{
							iPossibleTargets = min((pPlot->getNumVisibleEnemyDefenders(pLoopUnit->getOwnerINLINE()) - 1), pLoopUnit->collateralDamageMaxUnits());

							if (iPossibleTargets > 0)
							{
								iValue *= (100 + ((pLoopUnit->collateralDamage() * iPossibleTargets) / 5));
								iValue /= 100;
							}
						}

						// if non-human, prefer the last unit that has the best value (so as to avoid splitting the group)
						if (iValue > iBestValue || (!bIsHuman && iValue > 0 && iValue == iBestValue))
						{
							iBestValue = iValue;
							iBestOdds = iOdds;
							pBestUnit = pLoopUnit;
						}
					}
				}
				/* BetterAI by mrgenie 21.01.2007 end*/
			}
		}
	}

	/* BetterAI by mrgenie 21.01.2007 start*/
	iUnitOdds = iBestOdds;
	/* BetterAI by mrgenie 21.01.2007 end*/
	return pBestUnit;
}

/* BetterAI by mrgenie 21.01.2007 start*/
CvUnit* CvSelectionGroupAI::AI_getBestGroupSacrifice(const CvPlot* pPlot, bool bPotentialEnemy, bool bForce, bool bNoBlitz) const
{
	int iBestValue = 0;
	CvUnit* pBestUnit = NULL;

	CLLNode<IDInfo>* pUnitNode = headUnitNode();
	while (pUnitNode != NULL)
	{
		CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
		pUnitNode = nextUnitNode(pUnitNode);

		if (!pLoopUnit->isDead())
		{
			bool bCanAttack = false;
			if (pLoopUnit->getDomainType() == DOMAIN_AIR)
			{
				bCanAttack = pLoopUnit->canAirAttack();
			}
			else
			{
				bCanAttack = pLoopUnit->canAttack();

				if (bCanAttack && bNoBlitz && pLoopUnit->isBlitz() && pLoopUnit->isMadeAttack())
				{
					bCanAttack = false;
				}
			}

			if (bCanAttack)
			{
				if (bForce || pLoopUnit->canMove())
				{
					if (bForce || pLoopUnit->canMoveInto(pPlot, true))
					{
                        int iValue = pLoopUnit->AI_sacrificeValue(pPlot);
						FAssertMsg(iValue > 0, "iValue is expected to be greater than 0");

						// we want to pick the last unit of highest value, so pick the last unit with a good value
						if (iValue >= iBestValue)
						{
							iBestValue = iValue;
							pBestUnit = pLoopUnit;
						}
					}
				}
			}
		}
	}

	return pBestUnit;
}

// Returns ratio of strengths of stacks times 100
// (so 100 is even ratio, numbers over 100 mean this group is more powerful than the stack on a plot)
int CvSelectionGroupAI::AI_compareStacks(const CvPlot* pPlot, bool bPotentialEnemy, bool bCheckCanAttack, bool bCheckCanMove) const
{
	FAssert(pPlot != NULL);

	int	compareRatio;
	DomainTypes eDomainType = getDomainType();

	// if not aircraft, then choose based on the plot, not the head unit (mainly for transport carried units)
	if (eDomainType != DOMAIN_AIR)
	{
		if (pPlot->isWater())
			eDomainType = DOMAIN_SEA;
		else
			eDomainType = DOMAIN_LAND;

	}

	compareRatio = AI_sumStrength(pPlot, eDomainType, bCheckCanAttack, bCheckCanMove);
	compareRatio *= 100;

	PlayerTypes eOwner = getOwnerINLINE();
	if (eOwner == NO_PLAYER)
	{
		eOwner = getHeadOwner();
	}
	FAssert(eOwner != NO_PLAYER);

	int defenderSum = pPlot->AI_sumStrength(NO_PLAYER, getOwnerINLINE(), eDomainType, true, !bPotentialEnemy, bPotentialEnemy);
	compareRatio /= max(1, defenderSum);

	return compareRatio;
}

int CvSelectionGroupAI::AI_sumStrength(const CvPlot* pAttackedPlot, DomainTypes eDomainType, bool bCheckCanAttack, bool bCheckCanMove) const
{
	CLLNode<IDInfo>* pUnitNode;
	CvUnit* pLoopUnit;
	int	strSum = 0;

	pUnitNode = headUnitNode();

	while (pUnitNode != NULL)
	{
		pLoopUnit = ::getUnit(pUnitNode->m_data);
		pUnitNode = nextUnitNode(pUnitNode);

		if (!pLoopUnit->isDead())
		{
			bool bCanAttack = false;
			if (pLoopUnit->getDomainType() == DOMAIN_AIR)
				bCanAttack = pLoopUnit->canAirAttack();
			else
				bCanAttack = pLoopUnit->canAttack();

			if (!bCheckCanAttack || bCanAttack)
			{
				if (!bCheckCanMove || pLoopUnit->canMove())
					if (!bCheckCanMove || pAttackedPlot == NULL || pLoopUnit->canMoveInto(pAttackedPlot, /*bAttack*/ true, /*bDeclareWar*/ true))
						if (eDomainType == NO_DOMAIN || pLoopUnit->getDomainType() == eDomainType)
							strSum += pLoopUnit->currEffectiveStr(pAttackedPlot, pLoopUnit);
			}
		}
	}

	return strSum;
}

void CvSelectionGroupAI::AI_queueGroupAttack(int iX, int iY)
{
	m_bGroupAttack = true;

	m_iGroupAttackX = iX;
	m_iGroupAttackY = iY;
}

inline void CvSelectionGroupAI::AI_cancelGroupAttack()
{
	m_bGroupAttack = false;
}

inline bool CvSelectionGroupAI::AI_isGroupAttack()
{
	return m_bGroupAttack;
}
/* BetterAI by mrgenie 21.01.2007 end*/

bool CvSelectionGroupAI::AI_isControlled()
{
	return (!isHuman() || isAutomated());
}

/* BetterAI by mrgenie 21.01.2007 start*/
bool CvSelectionGroupAI::AI_isDeclareWar(const CvPlot* pPlot)
{
	FAssert(getHeadUnit() != NULL);

	if (isHuman())
	{
		return false;
	}
	else
	{
		bool bLimitedWar = false;
		if (pPlot != NULL)
		{
			TeamTypes ePlotTeam = pPlot->getTeam();
			if (ePlotTeam != NO_TEAM)
			{
				WarPlanTypes eWarplan = GET_TEAM(getTeam()).AI_getWarPlan(ePlotTeam);
				if (eWarplan == WARPLAN_LIMITED || eWarplan == WARPLAN_PREPARING_LIMITED)
				{
					bLimitedWar = true;
				}
			}
		}

		CvUnit* pHeadUnit = getHeadUnit();

		if (pHeadUnit != NULL)
		{
			switch (pHeadUnit->AI_getUnitAIType())
			{
			case UNITAI_UNKNOWN:
			case UNITAI_ANIMAL:
			case UNITAI_SETTLE:
			case UNITAI_WORKER:
			/*************************************************************************************************/
            /** Added by Mrgenie, 29/01/07                                                                   */
            /** UNITAI G ERA                                                                                 */
            /**                                                                                              */
            /*************************************************************************************************/
            case UNITAI_SEA_ENGINEER:
            /*************************************************************************************************/
            /*************************************************************************************************/
				break;

			case UNITAI_ATTACK:
			case UNITAI_ATTACK_CITY:
				return true;
				break;

			case UNITAI_COLLATERAL:
			case UNITAI_PILLAGE:
			case UNITAI_RESERVE:
			case UNITAI_COUNTER:
				if (bLimitedWar)
				{
					return true;
				}
				break;

			case UNITAI_CITY_DEFENSE:
			case UNITAI_CITY_COUNTER:
			case UNITAI_CITY_SPECIAL:
			case UNITAI_EXPLORE:
			case UNITAI_MISSIONARY:

			/*************************************************************************************************/
    		/** Added by Mrgenie, 21/02/07                                                                   */
    		/** INQUISITION                                                                                  */
    		/**                                                                                              */
    		/*************************************************************************************************/
			case UNITAI_INQUISITOR:
			/*************************************************************************************************/
    		/*************************************************************************************************/ 

			case UNITAI_PROPHET:
			case UNITAI_ARTIST:
			case UNITAI_SCIENTIST:
			case UNITAI_GENERAL:
			case UNITAI_MERCHANT:
			/*************************************************************************************************/
            /** Added by Mrgenie, 19/02/07                                                                   */
            /** UNITAI GREAT STATESMAN                                                                       */
            /**                                                                                              */
            /*************************************************************************************************/
            case UNITAI_STATESMAN:
            /*************************************************************************************************/
            /*************************************************************************************************/
			case UNITAI_ENGINEER:
			case UNITAI_SPY:
			/*************************************************************************************************/
            /** Added by Mrgenie, 29/01/07                                                                   */
            /** UNITAI G ERA                                                                                 */
            /**                                                                                              */
            /*************************************************************************************************/
            case UNITAI_CIVILIAN:
            /*************************************************************************************************/
            /*************************************************************************************************/
			case UNITAI_ICBM:
			case UNITAI_WORKER_SEA:
				break;

			case UNITAI_ATTACK_SEA:
			case UNITAI_RESERVE_SEA:
			case UNITAI_ESCORT_SEA:
			case UNITAI_EXPLORE_SEA:
				if (bLimitedWar)
				{
					return true;
				}
				break;

			case UNITAI_ASSAULT_SEA:
				return true;
				break;

			case UNITAI_SETTLER_SEA:
			case UNITAI_MISSIONARY_SEA:
			
			/*************************************************************************************************/
    		/** Added by Mrgenie, 21/02/07                                                                   */
    		/** INQUISITION                                                                                  */
    		/**                                                                                              */
    		/*************************************************************************************************/
			case UNITAI_INQUISITOR_SEA:
			/*************************************************************************************************/
    		/*************************************************************************************************/
			
			case UNITAI_SPY_SEA:
			/*************************************************************************************************/
            /** Added by Mrgenie, 29/01/07                                                                   */
            /** UNITAI G ERA                                                                                 */
            /**                                                                                              */
            /*************************************************************************************************/
			//case UNITAI_NUKE_SEA:
			/*************************************************************************************************/
            /*************************************************************************************************/

			case UNITAI_DEFENSE_AIR:
				break;

			case UNITAI_CARRIER_SEA:
			case UNITAI_ATTACK_AIR:
			case UNITAI_CARRIER_AIR:
				if (bLimitedWar)
				{
					return true;
				}
				break;

			default:
				FAssert(false);
				break;
			}
		}
	}

	return false;
}
/* BetterAI by mrgenie 21.01.2007 end*/

CvPlot* CvSelectionGroupAI::AI_getMissionAIPlot()
{
	return GC.getMapINLINE().plotSorenINLINE(m_iMissionAIX, m_iMissionAIY);
}


bool CvSelectionGroupAI::AI_isForceSeparate()
{
	return m_bForceSeparate;
}


void CvSelectionGroupAI::AI_makeForceSeparate()
{
	m_bForceSeparate = true;
}


MissionAITypes CvSelectionGroupAI::AI_getMissionAIType()
{
	return m_eMissionAIType;
}


void CvSelectionGroupAI::AI_setMissionAI(MissionAITypes eNewMissionAI, CvPlot* pNewPlot, CvUnit* pNewUnit)
{
	m_eMissionAIType = eNewMissionAI;

	if (pNewPlot != NULL)
	{
		m_iMissionAIX = pNewPlot->getX_INLINE();
		m_iMissionAIY = pNewPlot->getY_INLINE();
	}
	else
	{
		m_iMissionAIX = INVALID_PLOT_COORD;
		m_iMissionAIY = INVALID_PLOT_COORD;
	}

	if (pNewUnit != NULL)
	{
		m_missionAIUnit = pNewUnit->getIDInfo();
	}
	else
	{
		m_missionAIUnit.reset();
	}
}


CvUnit* CvSelectionGroupAI::AI_getMissionAIUnit()
{
	return getUnit(m_missionAIUnit);
}

// Protected Functions...

void CvSelectionGroupAI::read(FDataStreamBase* pStream)
{
	CvSelectionGroup::read(pStream);

	uint uiFlag=0;
	pStream->Read(&uiFlag);	// flags for expansion

	pStream->Read(&m_iMissionAIX);
	pStream->Read(&m_iMissionAIY);

	pStream->Read(&m_bForceSeparate);

	pStream->Read((int*)&m_eMissionAIType);

	pStream->Read((int*)&m_missionAIUnit.eOwner);
	pStream->Read(&m_missionAIUnit.iID);
}


void CvSelectionGroupAI::write(FDataStreamBase* pStream)
{
    //gDLL->logMsg("MAF.log", "CvSelectionGroupAI::write entered");
	CvSelectionGroup::write(pStream);

	uint uiFlag=0;
	pStream->Write(uiFlag);		// flag for expansion

	pStream->Write(m_iMissionAIX);
	pStream->Write(m_iMissionAIY);

	pStream->Write(m_bForceSeparate);

	pStream->Write(m_eMissionAIType);

	pStream->Write(m_missionAIUnit.eOwner);
	pStream->Write(m_missionAIUnit.iID);
    //gDLL->logMsg("MAF.log", "CvSelectionGroupAI::write exit");
}

// Private Functions...
